package net.starwifi.duobao.web;

import net.starwifi.duobao.AppInitListener;
import net.starwifi.duobao.entity.DBOrder;
import net.starwifi.duobao.entity.Refunds;
import net.starwifi.duobao.mvc.*;
import net.starwifi.duobao.plugin.PaymentPlugin;
import net.starwifi.duobao.service.*;
import net.starwifi.duobao.utils.times.DateTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller("adminDBOrderController")
@RequestMapping("/dbOrder")
public class DBOrderController extends BaseController {


    @Autowired
    DBTimesService dbTimesService;

    @Autowired
    DBProductService dbProductService;



    @Autowired
    DBOrderService dbOrderService;

    @Autowired
    RefundsService refundsService;

    @Autowired
    PluginService pluginService;

    @Autowired
    RefundHelperService refundHelperService;

    /**
     * 编辑
     */
    @ResponseBody
    @RequestMapping(value = "/batchRefunds", method = RequestMethod.GET)
    public Message batchRefunds(HttpServletRequest request) {
        refundHelperService.batchRefunds(request);
        return Message.success("");
    }


    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model) {
        model.addAttribute("entity", dbOrderService.find(id));
        return "/dbOrder/edit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(DBOrder entity,Long tid, RedirectAttributes redirectAttributes) {
        if (!isValid(entity)) {
            return ERROR_VIEW;
        }
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "/dbOrder/list?tid"+tid;
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public String list(PageView pageView,ModelMap model,HttpServletRequest request) {
        pageView.filterQuery(request);
        addDefaultFilter(pageView);
        pageView.addOrder(Order.desc("id"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        model.addAttribute("currentDate",format.format(new Date()));
        Date beginData= DateTool.setHms(new Date(), 0, 0, 0);
        Date endData= DateTool.setHms(new Date(),23,59,59);
        model.addAttribute("beginData", beginData);
        model.addAttribute("endData", endData);
        model.addAttribute("dbProductList",dbProductService.getListData());
        model.addAttribute("page", dbOrderService.getScrollData(pageView));
        model.addAttribute("amount", dbOrderService.getSumBigDecimal(pageView.getFilters(),"amount"));
        return "/dbOrder/listAll";
    }




    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(PageView pageView, Long tid,ModelMap model,HttpServletRequest request) {
        pageView.filterQuery(request);
        pageView.addFilter(Filter.eq("dbTimes.id", tid));
        pageView.addOrder(Order.desc("id"));
        model.addAttribute("dbProductList",dbProductService.find(tid));
        model.addAttribute("page", dbOrderService.getScrollData(pageView));
        return "redirect:/dbOrder/list?tid="+tid;
    }


    /**
     * 手动退款
     */
    @ResponseBody
    @RequestMapping(value = "/refund")
    public Message refunded(Long orderId,HttpServletRequest request){
        final DBOrder order=dbOrderService.find(orderId);
        if(order.getIsRefund()){
            return Message.error("已经手动退款过");
        }
        //TODO 应该修改为 findByOrderSnAndPaymentPluginId (同一个订单，同一种支付方法只允许有一个退款单)
        Refunds refunds=refundsService.findByOrderSn(order.getSn());
        if(refunds==null){
            refunds=new Refunds();
            refunds.setSn( AppInitListener.idGenerate.getID().toString());
            refunds.setMethod(Refunds.Method.online);
            refunds.setStatus(Refunds.Status.wait);
            refunds.setPaymentMethod(order.getPaymentMethodName());
            refunds.setAmount(order.getAmount());
            refunds.setOrderId(orderId);
            refunds.setOrderSn(order.getSn());
            refunds.setOperator("sys");
            //refunds.setFlag(order.getFlag());
            refundsService.save(refunds);
        }
        PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin("wo3DirectPlugin");
        if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
            return Message.error("支付插件错误");
        }
        Message message=paymentPlugin.refund(refunds,request);
        if(message.getType()== Message.Type.success){ //退款成功
            dbOrderService.refunds(order, refunds);
        }
        return message;
    }




    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Message delete(Long[] ids) {
        dbTimesService.delete(ids);
        return SUCCESS_MESSAGE;
    }


}
